package qlttn.web.bean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;

@ManagedBean
public class UploadImageBean {

    private UploadedFile uploadedFile;
    private static String imgPath;
    
    public UploadImageBean(){
    	
    }
    

    public String loadFile() {
    	HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
    	String path = request.getServletContext().getRealPath("/images");
    	
//    	String path = "D:/tai lieu fpt/tai lieu/update project/QLTTN/WebContent/images";
    	System.out.println(uploadedFile);
        String fileName = FilenameUtils.getName(uploadedFile.getName());
        imgPath = fileName.trim();
        File file = new File(path+"/"+imgPath);
        if(!file.exists()){
        	try {
    			byte[] bytes = uploadedFile.getBytes();
    			 
    			 System.out.println(imgPath+"...Ok");
    		        FileOutputStream fos = new FileOutputStream(path+"/"+imgPath);
    		        fos.write(bytes);
    		        fos.flush();
    		        fos.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
        }
        return "singleChoiceQuestion";
    }
    

    public UploadedFile getUploadedFile() {
    	if(uploadedFile !=null)
    	System.out.println(uploadedFile.getName());
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
        if(uploadedFile !=null)
        System.out.println(uploadedFile.getName());
    }


	public String getImgPath() {
		return imgPath;
	}


	public void setImgPath(String imgPath) {
		this.imgPath = imgPath;
	}
	
	public static String getPathImg(){
		return imgPath;
	}
    

}